const app = getApp()
const {
  navBarHeight,
  statusBarHeight,
  menuButton
} = app.globalData
const {
  baseURL
} = require('../fetch/http')
const api = require('../fetch/api')
import Dialog from '../miniprogram_npm/@vant/weapp/dialog/dialog';
Component({
  pageLifetimes: {
    show() {
    
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 2,
          num: ''
        })
      }
      this.clear()
      this.cart()
      if (wx.getStorageSync('token')) {
     
      }

    }
  },
  lifetimes: {
    attached() {

    }
  },
  data: {
    baseURL: baseURL,
    statusBarHeight: statusBarHeight,
    h: navBarHeight,
    w: menuButton.width,
    right: menuButton.right,
    bottomHeight: navBarHeight - statusBarHeight,
    arr: [],
    loading: false,
    finished: false,
    page: 1,
    sum: 0, // 总计
    isSelectedAll: false, // 是否全选
    isEdit: false // 是否为编辑状态
  },
  methods: {
    back() {
      wx.navigateBack()
    },
    pay() {
      let arr = this.data.arr.filter(n => n.selected)
      let str = arr.map(n => n.id).join(',')
      // console.log(str);
      wx.navigateTo({
        url: '/pages/my/settle/index?id=' + str,
      })
    },
    toggleState() {
      let {
        isEdit
      } = this.data
      this.setData({
        isEdit: !isEdit
      })
    },
    async add(e) {
      const {
        index,
        id
      } = app.dataSet(e)
      let item = this.data.arr[index]
      // 当前数量小于库存量 
      if (item.num < item.sku) {
        item.num++
      } else {
        app.toast('库存不足')
        return
      }
      let res = await api.cartChange({
        cart_id: id,
        num: item.num
      })
      this.setData({
        [`arr[${index}].num`]: item.num
      })
      this.computedSum()
    },
    async reduce(e) {
      const {
        index,
        id
      } = app.dataSet(e)
      let item = this.data.arr[index]
      if (item.num == 1) {
        // app.toast('最少购买一件哦～')
        return
      }
      item.num--
      let res = await api.cartChange({
        cart_id: id,
        num: item.num
      })
      this.setData({
        [`arr[${index}].num`]: item.num
      })
      this.computedSum()
    },
    async remove() {
      let array = this.data.arr.filter(item => item.selected)
      Dialog.confirm({
          title: `确认要删除${array.length}件商品吗？`,
          message: '点击确认继续',
        })
        .then(() => {
          api.cartDel({
            cart_id: array.map(n => n.id)
          }).then(res => {
            this.clear()
            this.cart()
            this.computedSum()
          })
        })
        .catch(() => {
          // on cancel
        });
    },
    // 判断是否全选
    isSelectedAll() {
      let flag = true // 默认全选
      let array = this.data.arr
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element.selected === false) {
          flag = false;
          break;
        }
      }
      this.setData({
        isSelectedAll: flag
      })
    },
    // 计算总金额
    computedSum() {
      let arr = this.data.arr.filter(n => n.selected)
      let sum = arr.reduce((accumulator, currentValue) => {
        if (currentValue.selected) {
          return accumulator + (currentValue.num * currentValue.price * 100)
        } else {
          return accumulator
        }
      }, 0)
      this.setData({
        sum: (sum / 100).toFixed(2)
      })
    },
    // 全选/全不选
    toggleSelectedAll() {
      let {
        isSelectedAll
      } = this.data
      this.setData({
        isSelectedAll: !isSelectedAll
      })
      let array = [...this.data.arr]
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        element.selected = !isSelectedAll
      }
      this.setData({
        arr: array
      })
      this.computedSum()
    },
    async toggle(e) {
      const {
        index,
        id
      } = app.dataSet(e)
      let item = this.data.arr[index]
      this.setData({
        [`arr[${index}].selected`]: !item.selected
      })
      this.isSelectedAll()
      this.computedSum()
    },
    async cart() {
      if (!this.data.loading) {
        this.setData({
          loading: true
        })
        let res = await api.cart({
          page: this.data.page,
        })
        let newArr = res.data.map(n => {
          n.selected = false
          return n
        })
        let finished = false
        res.data.length == 0 && (finished = true)
        this.setData({
          arr: [...this.data.arr, ...newArr],
          finished,
          loading: false
        })
      }
    },
    clear() {
      this.setData({
        page: 1,
        loading: false,
        finished: false,
        arr: []
      })
    },
    async show() {
    
    },
    onShareAppMessage: function () {
      if (!wx.getStorageSync('token')) {
        app.toast('请登录')
        return false
      }

      return {
        title: '天喜鑫宝',
        imageUrl: this.data.baseURL + '/img/share_img_2.png',
        path: '/index/index4?id=' + wx.getStorageSync('id')
      }
    }
  }
})